/**
* 注册
*/
import React, { Component } from 'react';
import { View, StyleSheet, Text, Image, TouchableOpacity, TextInput, DeviceEventEmitter } from "react-native";
import { connect } from 'react-redux';
import { create_service } from '../../redux/index.js';
import { Contract } from '../../service/index.js';
import { Colors, Dimens, ImageRes } from '../../utils/Assets';
import { ProgressView } from '../custom/index'
import { Actions } from 'react-native-router-flux';
import { getStore } from '../../redux/index.js';
import Toast from 'react-native-root-toast';
import ScrollableTabView from 'react-native-scrollable-tab-view'

class TeamChangeRateView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            searchMonth: "",
            searchTime: '',
            currentIndex: 0,
            tabbarName: ['余额智还', '快捷收银'],
            rightTitle: '管理',
            refreshing: false,
            delete: false,
            rightTitle: '管理',
        }
        this.userInfo = getStore().getState().auth.userInfo
    }

    componentDidMount() {
        this.listener = DeviceEventEmitter.addListener('ChangeIndex', (value) => {
            this.setState({ currentIndex: value.index })
        })
    }
    componentWillUnmount() {
        this.listener && this.listener.remove()
    }

    render() {
        return (
            <View style={styles.container}>
                <ScrollableTabView
                    locked={true}
                    renderTabBar={() => <TabBar />}>
                    {
                        this.state.tabbarName.map((item, index) => {
                            return (
                                <TeamChangeRateTab key={index} tabLabel={item} index={index} dispatch={this.props.dispatch} userInfo={this.userInfo} users_id={this.props.users_id} delete={this.state.delete} editable={this.props.editable} />
                            )
                        })
                    }
                </ScrollableTabView>
            </View>
        )
    }
}


const TabBar = (props) => {
    let { tabs, activeTab, goToPage } = props;
    return (
        <View style={{ backgroundColor: Colors.white_color, width: Dimens.DeviceWidth, height: 50, flexDirection: 'row' }}>
            {tabs.map((tab, i) => (
                <TouchableOpacity onPress={() => {
                    goToPage(i)
                    DeviceEventEmitter.emit('ChangeIndex', { index: i })
                }} activeOpacity={0.8} key={i} style={{ flex: 1, height: 50, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 15, backgroundColor: Colors.white_color }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={{ color: (activeTab == i ? '#378EFB' : "#333333"), fontSize: 14, alignSelf: 'center' }}>{tab}</Text>
                    </View>
                    <View style={{ width: 100, height: 3, backgroundColor: (activeTab == i ? "#378EFB" : 'transparent'), position: 'absolute', bottom: 0, alignSelf: 'center' }} />
                </TouchableOpacity>
            ))}
        </View>
    )
}

class TeamChangeRateTab extends Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            largeRate: "",
            smallRate: "",
            rate : [],
            repayment_fee: 0
        }
        this.userInfo = getStore().getState().auth.userInfo
    }

    componentDidMount() {
        this.getRate()
    }
    getRate() {
        let that = this
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.POST_USER_PAYMENT_CONFIG, {
            token: this.userInfo.token,
            user_id: this.props.users_id,
            config_type: that.props.index + 1
        })).then((res) => {
            if (res) {
                this.setState({ loading: false, rate: res, repayment_fee:res[0].repayment_fee })
            } else {
                this.setState({ loading: false, largeRate: "", smallRate: "" })
            }
        })
    }
    changeRate() {
        let that = this
        this.setState({ loading: true })
        
        let largeRate = 0;
        let smallRate = 0;

        for(let i = 0; i < this.state.rate.length; i++){
            console.log(this.state.rate)
            if(this.state.rate[i].config_type == this.props.index + 1 ) {
                if(this.state.rate[i].channel_type == '大额'){
                    largeRate = this.state.rate[i].consume_rate
                }else if(this.state.rate[i].channel_type == '小额'){
                    smallRate = this.state.rate[i].consume_rate
                }
            }
        }

        this.props.dispatch(create_service(Contract.POST_USER_UPDATE_PAYMENT_CONFIG, {
            token: this.userInfo.token,
            user_id: this.props.users_id,
            config_type: that.props.index + 1,
            large: largeRate,
            small: smallRate,
            repayment_fee: this.state.repayment_fee
        })).then((res) => {
            if (res) {
                Toast.show('修改成功', { position: Toast.positions.CENTER })
                Actions.pop()
            }
            this.setState({ loading: false })
        })
    }
    setRate(index, channelType, rate){
        console.log(rate)
        let newRate = [];
        for(let i = 0; i < this.state.rate.length; i++){
            newRate[i] = this.state.rate[i]
            if(newRate[i].config_type == index + 1 
                &&
                newRate[i].channel_type == channelType
            ){
                newRate[i].consume_rate = rate * 0.0001
                newRate[i].consume_rate.toFixed(4)
            }
        }

        this.setState({
            rate: newRate
        })
    }

    render() {
        return (
            <View style={styles.container}>
                {
                    this.state.rate.map((item) => {
                        return (
                            <View style={{ backgroundColor: "#ffffff", paddingHorizontal: 15, marginTop: 15, flexDirection: 'row', alignItems:'center' }}>
                                <Text style={{ fontSize: 18, color: "#333333", marginLeft: 15, width:120 }}>{item.channel_type}费率</Text>
                                <TextInput style={{ fontSize: 18, color: '#333333', height: 50, paddingHorizontal: 15, flex: 1, textAlign:'center' }}
                                    onChangeText={(text) => {
                                        this.setRate(this.props.index, item.channel_type, text)
                                        // this.setState({ rate: text, channel_type: item.channel_type })
                                    }}
                                    placeholderTextColor={'#999999'}
                                    underlineColorAndroid={'transparent'}
                                    placeholder={'请填写'+item.channel_type+'费率'}
                                    value={item.consume_rate && (item.consume_rate * 10000).toFixed(0)}
                                    keyboardType={'number-pad'}
                                    editable={this.props.editable}
                                />
                                <Text style={{ fontSize: 18, color: "#FC2222", alignSelf: 'center' }}>/万</Text>
                            </View>
                        )})
                }
               
                <View style={{ backgroundColor: "#ffffff", paddingHorizontal: 15, marginTop: 15, flexDirection: 'row', alignItems:'center' }}>
                    <Text style={{ fontSize: 18, color: "#333333", marginLeft: 15 , width:120}}>笔  数  费</Text>
                    <TextInput style={{ fontSize: 18, color: '#333333', height: 50, paddingHorizontal: 15, flex: 1, textAlign:'center' }}
                        onChangeText={(text) => {
                            this.setState({ repayment_fee: text })
                        }}
                        placeholderTextColor={'#999999'}
                        underlineColorAndroid={'transparent'}
                        placeholder={'请填写笔数'}
                        value={this.state.repayment_fee && this.state.repayment_fee.toString()}
                        keyboardType={'number-pad'}
                        editable={this.props.editable}
                    />
                    <Text style={{ fontSize: 18, color: "#FC2222", alignSelf: 'center' }}>/笔</Text>
                </View>
                {this.props.editable && <TouchableOpacity style={{ marginTop: 50, backgroundColor: '#378EFB', justifyContent: 'center', marginHorizontal: 15, paddingVertical: 15, borderRadius: 5 }} activeOpacity={0.8} onPress={() => {
                    this.changeRate()
                }}>
                    <Text style={{ fontSize: 15, color: "#ffffff", alignSelf: 'center' }}>完成</Text>
                </TouchableOpacity>}
                <ProgressView show={this.state.loading} />
            </View>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        backgroundColor: Colors.bg_color,
        paddingBottom: Dimens.isIPhoneX ? 15 : 0,
        flex: 1
    }
});
const ExportView = connect()(TeamChangeRateView);
ExportView.renderTitle = (props) => {
    return (
        <View style={{ flex: 1, justifyContent: 'center' }}>
            <Text style={{ alignSelf: 'center', fontSize: 18, color: "#ffffff" }} numberOfLines={1}>{props.title}</Text>
        </View>
    )
}
module.exports.TeamChangeRateView = ExportView
